package com.gem.web;

import com.gem.entity.Admin;
import com.gem.service.AdminService;
import com.gem.service.CommodityService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    CommodityService commodityService;
    @Autowired
    AdminService adminService;

    @GetMapping(value = "/toLogin")
    public String admin(){
        return "/admin/login";
    }

    @RequestMapping("/login")
    @ResponseBody
    public String login(String username,String password){
        Admin admin = adminService.login(username,password);
        if (admin == null){
            //登录失败
            return "0";
        }
        return "1";
    }

    @RequestMapping("/toManage")
    public String toManage(){
        return "/admin/manage";
    }


    @RequestMapping("/demo")
    public String demo(Model model){
        List<String> types = commodityService.findAllType();
        String str = "[";
        for (int i = 0; i < types.size(); i++) {
            str += "\'" + types.get(i) + "\'";
            if (i != types.size()-1){
                str += ",";
            }
        }
        str += "]";
        model.addAttribute("types",str);

        StringBuilder data = new StringBuilder("[");
        List<Map<String, String>> typeAndNum = commodityService.findNumByType();
        for (int i = 0; i < typeAndNum.size(); i++) {
            data.append("{");
            data.append("value:" + typeAndNum.get(i).get("num") + ", name:\'" + typeAndNum.get(i).get("type") + "\'");
            data.append("}");
            if (i != typeAndNum.size()-1){
                data.append(",");
            }
        }
        data.append("]");
        model.addAttribute("data",data);
        return "/admin/demo";
    }

    @RequestMapping("/showAllCommodity")
    public String showAllCommodity(Model model,String name,Integer pageNow){
        System.out.println("进入展示所有方法");
        if (pageNow == null){
            pageNow = 1;
        }
        PageInfo pageInfo = commodityService.findCommoditysByName(pageNow,7,name);
        model.addAttribute(pageInfo);
        return "/admin/showAllCommodity";
    }

    @RequestMapping("/addCommodity")
    public String addCommodity(){
        return "/admin/addCommodity";
    }
}
